package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"strings"
	"time"
)

func main() {
	// 输入视频文件路径和输出目录
	fileName := "招魂二"
	inputFile := fileName + ".mp4"
	outputDir := fmt.Sprintf("./%s/", fileName)

	// 如果输出目录不存在，创建它
	err := os.MkdirAll(outputDir, 0755)
	if err != nil {
		log.Fatalf("Failed to create output directory: %s\n", err)
	}

	// 获取视频总时长
	duration, err := getVideoDuration(inputFile)
	if err != nil {
		log.Fatalf("Failed to get video duration: %s\n", err)
	}

	// 每隔十分钟分割一次
	splitDuration := 15 * time.Minute
	startTime := time.Duration(0)
	// ...
	var fileIndex = 0
	for startTime < duration {
		endTime := startTime + splitDuration
		if endTime > duration {
			endTime = duration
		}

		fileIndex += 1
		// 根据 startTime 和 endTime 分割视频
		outputFile := fmt.Sprintf("%s%s-%d.mp4", outputDir, fileName, fileIndex)
		cmd := exec.Command("ffmpeg",
			"-i", inputFile,
			"-ss", formatDuration(startTime), // 将起始时间秒数格式化为字符串
			"-to", formatDuration(endTime), // 将结束时间秒数格式化为字符串
			"-c", "copy",
			outputFile,
		)

		// 执行命令
		fmt.Printf("Executing command: %s\n", strings.Join(cmd.Args, " "))
		err := cmd.Run()
		if err != nil {
			log.Fatalf("Error while executing ffmpeg: %s\n", err)
		}

		fmt.Printf("Successfully split segment from %s to %s\n", formatDuration(startTime), formatDuration(endTime))

		// 更新 startTime 为下一个视频段的开始时间
		startTime = endTime
	}
	// ...

}

// 获取视频文件的总时长
func getVideoDuration(filename string) (time.Duration, error) {
	cmd := exec.Command("ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filename)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return 0, err
	}

	durationStr := strings.TrimSpace(string(output))
	durationSec, err := time.ParseDuration(durationStr + "s")
	if err != nil {
		return 0, err
	}

	return durationSec, nil
}

// 格式化时间为 HHMMSS 格式
func formatDuration(d time.Duration) string {
	totalSeconds := int(d.Seconds())
	hours := totalSeconds / 3600
	minutes := (totalSeconds % 3600) / 60
	seconds := totalSeconds % 60
	//milliseconds := d.Milliseconds() % 1000

	return fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds)
}
